package com.alipay.rebate.shop.helper;

import com.alipay.rebate.shop.dao.mapper.HtmlClickMapper;
import com.alipay.rebate.shop.model.HtmlClick;
import com.alipay.rebate.shop.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class HtmlClickHelper {

    private final Logger logger = LoggerFactory.getLogger(HtmlClickHelper.class);

    @Autowired
    HtmlClickMapper htmlClickMapper;

    public void checkInterfaceClick(String htmlName,String htmlChineseName){

        logger.debug("htmlName is : {}",htmlName);
        logger.debug("htmlChineseName is : {}",htmlChineseName);

        try{
            //获取当天日期开始时间
            Date nowDate = DateUtil.getStartTimeOfToday();
            logger.debug("nowDate");

            //查询记录是否存在
            HtmlClick selectHtmlClick = htmlClickMapper.selectHtmlClick(htmlName, htmlChineseName, nowDate);
            logger.debug("selectHtmlClick is : {}",selectHtmlClick);
            insertOrUpdateHtmlClick(selectHtmlClick,htmlName,htmlChineseName,nowDate);
            if (htmlChineseName == null){
                HtmlClick htmlClick = htmlClickMapper.selectHtmlClickByHtmlName(htmlName, nowDate);
                insertOrUpdateHtmlClick(selectHtmlClick,htmlName,htmlChineseName,nowDate);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("checkExtra exception is : {}",e.getMessage());
        }

    }

    public List<HtmlClick> getHtmlClick(Date thySameDay){
        List<HtmlClick> htmlClicks = htmlClickMapper.selectHtmlClickAll(thySameDay);
        return htmlClicks;
    }

    private void insertOrUpdateHtmlClick(HtmlClick selectHtmlClick,String htmlName,String htmlChineseName,Date nowDate){
        int result;
        //不存在
        if (selectHtmlClick == null){
            HtmlClick htmlClick = new HtmlClick();
            htmlClick.setClickCount(1l);
            htmlClick.setHtmlName(htmlName);
            htmlClick.setHtmlChineseName(htmlChineseName);
            htmlClick.setTheSameDay(nowDate);
            logger.debug("htmlClick is : {}",htmlClick);
            result = htmlClickMapper.insertHtmlClick(htmlClick);

        }else{
            Date udpateTime = new Date();
            if (htmlChineseName != null) {
                //存在则更新记录
                result = htmlClickMapper.updateHtmlClick(htmlName, htmlChineseName, nowDate, udpateTime);
            }else{
                result = htmlClickMapper.updateHtmlClickByHtmlName(htmlName,nowDate,udpateTime);
            }
        }
        logger.debug("result is : {}",result);
    }

}
